<template>
  <el-dialog v-model="dialogVisible" fullscreen>
    <el-row :gutter="20">
      <el-col :span="6" :xs="24">
        <ContentWrap>
          <el-table highlight-current-row height="400" :header-cell-style="{ background: '#e6f7ef', color: '#008c46' }"
            row-key="id" :data="Typelist" :stripe="true" :show-overflow-tooltip="true" border
            @cell-click="handleCellClick">
            <el-table-column label="分类名称" align="center" prop="name" />
          </el-table>
        </ContentWrap>
      </el-col>
      <el-col :span="18" :xs="24">
        <ContentWrap>
          <el-button type="primary" plain @click="addConfig('add')">
            <Icon icon="ep:plus" class="mr-5px" /> 添加
          </el-button>
          <el-table @selection-change="handleRowCheckboxChange" height="400" border
            :header-cell-style="{ background: '#e6f7ef', color: '#008c46' }" row-key="id" v-loading="loading"
            :data="list" :stripe="true" :show-overflow-tooltip="true">
            <el-table-column type="selection" width="55" />
            <el-table-column label="分类" align="center" prop="typeName" width="150" />
            <el-table-column label="审核项" align="center" prop="name" />
          </el-table>
        </ContentWrap>
      </el-col>
    </el-row>
    <el-divider content-position="left">已绑定的审核项</el-divider>
    <el-row :gutter="20">
      <el-col :span="24" :xs="24">
        <ContentWrap>
          <el-button type="primary" plain @click="addConfig('delete')">
            <Icon icon="ep:delete" class="mr-5px" /> 移除
          </el-button>
          <el-table height="300" border @selection-change="bindChange"
            :header-cell-style="{ background: '#e6f7ef', color: '#008c46' }" row-key="id" :data="bindList"
            :stripe="true" :show-overflow-tooltip="true">
            <el-table-column type="selection" width="55" />
            <el-table-column label="分类" align="center" prop="typeName" width="150" />
            <el-table-column label="审核项" align="center" prop="name" />
          </el-table>
        </ContentWrap>
      </el-col>
    </el-row>


  </el-dialog>
</template>
<script setup lang="ts">
import { AuditLevelApi, AuditLevel } from '@/api/business/auditlevel'
import { dateFormatter } from '@/utils/formatTime'
import { isEmpty } from '@/utils/is'
import { AuditTypeApi, AuditConfig } from '@/api/business/audittype'

/** 审核等级 表单 */
defineOptions({ name: 'AuditLevelForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  levelName: undefined,
  description: undefined,
  configId: [],
  configDOList: []
})
const formRef = ref() // 表单 Ref


const loading = ref(false) // 列表的加载中
const list = ref([]) // 列表的数据
const Typelist = ref([]) // 列表的数据
const bindList = ref([])
const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: AuditLevel[]) => {
  checkedIds.value = records.map((item) => item.id);
}

const deleteCheckedIds = ref<number[]>([])
const bindChange = (records: AuditLevel[]) => {
  deleteCheckedIds.value = records.map((item) => item.id);
  console.log("deleteCheckedIds", deleteCheckedIds.value);
}


const levelId = ref()

/** 打开弹窗 */
const open = async (id?: number) => {
  levelId.value = id
  getTyoeList()
  await getList()
  dialogVisible.value = true
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await AuditLevelApi.getAuditLevel(id)
      bindList.value = formData.value.configDOList

    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗


const auditTypeId = ref(0)

const handleCellClick = (row) => {
  auditTypeId.value = row.id
  getList()

}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    list.value = await AuditTypeApi.getAuditConfigListByAuditTypeIdWait(auditTypeId.value, levelId.value)
  } finally {
    loading.value = false
  }
}

const getTyoeList = async () => {
  const data = await AuditTypeApi.getAuditTypeList()
  Typelist.value = data
}


const addConfig = async (type) => {

  if (type == "add") {
    console.log("选中的审核项", checkedIds.value);
    formData.value.configId.push(...checkedIds.value)
    const data = formData.value as unknown as AuditLevel
    await AuditLevelApi.updateAuditLevel(data)
    message.success("提交成功")
    formData.value = await AuditLevelApi.getAuditLevel(levelId.value)
    bindList.value = formData.value.configDOList
    getList()
  } else if (type == "delete") {

    const ids = formData.value.configId; // 全部ID
    const deleteIds = deleteCheckedIds.value; // 要删除的ID子集

    // 删除子集，得到剩余的ID
    const remainingIds = ids.filter(id => !deleteIds.includes(id));
    formData.value.configId = remainingIds
    console.log("remainingIds", remainingIds);
    const data = formData.value as unknown as AuditLevel
    await AuditLevelApi.updateAuditLevel(data)
    formData.value = await AuditLevelApi.getAuditLevel(levelId.value)
    bindList.value = formData.value.configDOList
    message.success("提交成功")
    getList()
  }


}


/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as AuditLevel
    await AuditLevelApi.updateAuditLevel(data)
    message.success("提交成功")
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    levelName: undefined,
    description: undefined,
    configId: [],
    configDOList: []
  }
  formRef.value?.resetFields()
}
</script>
